package admin

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"gitee.com/cxssang/goframe/lib/utils"

	"gitee.com/cxssang/goframe/lib/page"

	"gitee.com/cxssang/goframe/lib/sql"

	. "gitee.com/cxssang/genealogy/act"
)

func init() {
	HandleFunMap["/admin/members/list"] = func(w http.ResponseWriter, r *http.Request) {
		_page := r.FormValue("page")
		if _page == "" || _page == "0" {
			_page = "1"
		}
		p, _ := strconv.Atoi(_page)
		pager := page.NewPage(p-1, 40)
		name := r.FormValue("name")
		where := sql.NewWhere().Add("a.parent_id>0")
		if name != "" {
			where.Add("a.name like ?", fmt.Sprintf("%%%s%%", name))
		}
		sq := sql.New()
		//rows, err := sq.Select("members", where, pager.Offset(), pager.Size(), "*", "id desc").FetchAll()
		rows, err := sq.Raw("select a.*,b.id as uid,b.disabled from members a left join users b on (b.member_id=a.id) where ").Concat(where.String()).SetParams(where.GetParams()...).Concat(" order by a.id desc limit ?,?").AddParams(pager.Offset(), pager.Size()).FetchAll()
		if err != nil {
			DisplayError(w, err.Error())
			return
		}
		total, err := sq.Count("members as a", where, "a.id")
		if err != nil {
			DisplayError(w, err.Error())
			return
		}
		var parentIds []interface{}
		_ = rows.ForEach(func(index int, row *sql.Row) (bool, error) {
			parentIds = append(parentIds, row.Get("parent_id"))
			if row.Get("sex") == "" {
				row.Set("sex", "未知")
			} else {
				row.Set("sex", SexMap2[row.Get("sex")])
			}
			return true, nil
		})
		if len(parentIds) > 0 {
			symbols := strings.Repeat("?,", len(parentIds))
			symbols = strings.TrimRight(symbols, ",")
			rows2, err := sq.Select("members", sql.NewWhere().Add("id in ("+symbols+")", parentIds...), 0, 0, "id,name", "id desc").FetchAll()
			if err != nil {
				DisplayError(w, err.Error())
				return
			}
			for i, row2 := range rows {
				if row2.Get("parent_id") == "0" {
					row2.Set("parent_name", "始祖")
					continue
				}
				for _, row := range rows2 {
					if row2.Get("parent_id") == row.Get("id") {
						rows[i].Set("parent_name", row.Get("name"))
					}
				}
			}
		}

		paginator := pager.GetPaginator(total)
		Display(w, r, "admin/members/list", map[string]interface{}{
			"rows":      rows,
			"total":     total,
			"paginator": paginator,
		})
	}
	HandleFunMap["/admin/members/add"] = func(w http.ResponseWriter, r *http.Request) {
		var data map[string]interface{}
		jsonData := r.FormValue("data")
		var err error
		if jsonData != "" {
			err = json.Unmarshal([]byte(jsonData), &data)
		}
		if err != nil {
			JsonError(w, err.Error())
			return
		}
		var father string
		var members []interface{}
		if val, ok := data["parentId"]; ok {
			father, _ = val.(string)
		}
		if father == "" {
			JsonError(w, "请选择父亲")
			return
		}
		if val, ok := data["members"]; ok {
			members, _ = val.([]interface{})
		}

		if len(members) == 0 {
			JsonError(w, "请添加成员")
			return
		}
		sq := sql.Raw("insert into members(name,sex,birth,spouse,parent_id,address,phone,remark) values(?,?,?,?,?,?,?,?)")
		stmt, _ := sq.Prepare()
		stmt2, _ := sql.Raw("update members set sort=? where id=?").Prepare()
		for _, val := range members {
			member, ok := val.(map[string]interface{})
			if !ok {
				JsonError(w, "数据错误")
				return
			}
			var name string
			if val2, _ := member["name"]; ok {
				name, _ = val2.(string)
				if name == "" {
					JsonError(w, "请输入姓名")
					return
				}
			} else {
				JsonError(w, "请输入姓名")
				return
			}
			sex, _ := member["sex"]
			birth, _ := member["birth"]
			spouse, _ := member["spouse"]
			address, _ := member["address"]
			phone, _ := member["phone"]
			remark, _ := member["remark"]
			ret, err := stmt.Exec(name, sex, birth, spouse, father, address, phone, remark)
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			id, _ := ret.LastInsertId()
			_, err = stmt2.Exec(id, id)
			if err != nil {
				JsonError(w, err.Error())
				return
			}
		}
		JsonSuccess(w, nil)
	}

	HandleFunMap["/admin/members/query"] = func(w http.ResponseWriter, r *http.Request) {
		keyword := r.FormValue("keyword")
		where := sql.NewWhere()
		if keyword != "" {
			where.Add("name like ?", fmt.Sprintf("%s%s%s", "%", keyword, "%"))
		}
		rows, err := sql.New().Select("members", where, 0, 20, "id,name,parent_id", "id desc").FetchAll()
		if err != nil {
			DisplayError(w, err.Error())
			return
		}
		//父
		var parentIds []interface{}
		for _, row := range rows {
			parentIds = append(parentIds, row.Get("parent_id"))
		}
		if len(parentIds) > 0 {
			symbols := strings.Repeat("?,", len(parentIds))
			symbols = strings.TrimRight(symbols, ",")
			rows2, err := sql.New().Select("members", sql.NewWhere().Add("id in ("+symbols+")", parentIds...), 0, 0, "id,name", "id desc").FetchAll()
			if err != nil {
				DisplayError(w, err.Error())
				return
			}
			for _, row2 := range rows {
				if row2.Get("parent_id") == "0" {
					row2.Set("parent_name", "始祖")
					continue
				}
				for _, row := range rows2 {
					if row2.Get("parent_id") == row.Get("id") {
						row2.Set("parent_name", row.Get("name"))
					}
				}
			}
		}
		Display(w, r, "admin/members/query", map[string]interface{}{
			"rows": rows,
		})
	}

	HandleFunMap["/admin/members/edit"] = func(w http.ResponseWriter, r *http.Request) {
		id := r.FormValue("id")
		name := r.FormValue("name")
		sex := r.FormValue("sex")
		spouse := r.FormValue("spouse")
		birth := r.FormValue("birth")
		parentId := r.FormValue("parent_id")
		address := r.FormValue("address")
		phone := r.FormValue("phone")
		sort := r.FormValue("sort")
		remark := r.FormValue("remark")
		if CheckEmpty(w, id, "ID不能为空", name, "姓名不能为空", sex, "性别不能为空") {
			return
		}
		if sort == "" {
			sort = "99"
		}
		sq := sql.New()
		_, err := sq.Update("members", sql.NewWhere().Add("id=?", id), map[string]interface{}{
			"name":      name,
			"sex":       sex,
			"spouse":    spouse,
			"birth":     birth,
			"parent_id": parentId,
			"address":   address,
			"phone":     phone,
			"sort":      sort,
			"remark":    remark,
		}).Exec()
		if err != nil {
			JsonError(w, err.Error())
			return
		}
		JsonSuccess(w, nil)
	}

	HandleFunMap["/admin/members/tree"] = func(w http.ResponseWriter, r *http.Request) {
		sq := sql.New()
		rows, err := sq.Select("members", sql.NewWhere(), 0, 0, "id,name,spouse,sex,birth,parent_id", "sort asc").FetchAll()
		if err != nil {
			DisplayError(w, err.Error())
			return
		}
		if rows == nil {
			rows = sql.Rows{}
		}

		var nodes []*Node
		for _, row := range rows {
			node := &Node{
				ID:       row.GetInt("id"),
				Name:     row.Get("name"),
				ParentID: row.GetInt("parent_id"),
				Spouse:   row.Get("spouse"),
				Sex:      row.Get("sex"),
				Birth:    row.Get("birth"),
			}
			nodes = append(nodes, node)
		}
		tree := BuildTree(nodes, 0)

		Display(w, r, "admin/members/tree", map[string]interface{}{
			"tree": CreateTree(tree),
		})
	}

	HandleFunMap["/admin/members/delete"] = func(w http.ResponseWriter, r *http.Request) {
		id := r.FormValue("id")
		if CheckEmpty(w, id, "ID不能为空") {
			return
		}
		sq := sql.New()
		_, err := sq.Delete("members", sql.NewWhere().Add("id=?", id)).Exec()
		if err != nil {
			JsonError(w, err.Error())
			return
		}
		JsonSuccess(w, nil)
	}

	HandleFunMap["/admin/members/createUsers"] = func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			sq := sql.New()
			rows, err := sq.Select("members", sql.NewWhere().Add("parent_id!=0"), 0, 0, "id,name", "id desc").FetchAll()
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			for _, row := range rows {
				name := row.Get("name")
				memberId := row.Get("id")
				where := sql.NewWhere().Add("member_id=?", memberId)
				user, _ := sq.Select("users", where, 0, 0, "id", "").FetchOne()
				if user == nil {
					_, err = sq.Insert("users", map[string]interface{}{
						"name":      name,
						"password":  utils.Md5("123456"),
						"member_id": row.Get("id"),
						"is_admin":  "0",
					}).Exec()
					if err != nil {
						JsonError(w, err.Error())
						return
					}
				} else {
					_, err = sq.Update("users", where, map[string]interface{}{
						"name": name,
					}).Exec()
				}
			}
			JsonSuccess(w, nil)
		}
	}

	HandleFunMap["/admin/members/resetPswd"] = func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			id := r.FormValue("id")
			if CheckEmpty(w, id, "ID不能为空") {
				return
			}
			if id == "0" {
				JsonError(w, "ID不能为空")
				return
			}
			sq := sql.New()
			_, err := sq.Update("users", sql.NewWhere().Add("id=?", id), map[string]interface{}{
				"password": utils.Md5("123456"),
			}).Exec()
			if err != nil {
				JsonError(w, err.Error())
				return
			}
			JsonSuccess(w, nil)
		}
	}

	HandleFunMap["/admin/members/disableLogin"] = func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			id := r.FormValue("id")
			status := r.FormValue("status")
			if CheckEmpty(w, id, "ID不能为空") {
				return
			}
			if id == "0" {
				JsonError(w, "ID不能为空")
				return
			}
			if status != "0" && status != "1" {
				status = "1"
			}
			sq := sql.New()
			_, err := sq.Update("users", sql.NewWhere().Add("id=?", id), map[string]interface{}{
				"disabled": status,
			}).Exec()
			if err != nil {
				JsonError(w, err.Error())
			}
			JsonSuccess(w, nil)
		}
	}
}
